<template>
  <my-container>
    <!--查询-->
    <template #header>
      <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>
        <el-form-item>
          <el-input v-model="filter.name" placeholder="分类名称" clearable  @keyup.enter.native="onGetList">
            <template #prefix>
              <i class="el-input__icon el-icon-search" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onGetList">查询</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['api:material:articlecategory:add'])">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </template>
    <!--查询-->
    <!--列表-->
    <el-table
      ref="multipleTable"
      v-loading="listLoading"
      row-key="id"
      :data="articleCategoryTree"
      :default-expand-all="false"
      :expand-row-keys="expandRowKeys"    
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      highlight-current-row
      height="'100%'"
      style="width: 100%;height:100%;"
      @select-all="onSelectAll"
      @select="onSelect"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" width="50" label="#" />
      <el-table-column prop="name" label="分类名称" width />
      <el-table-column prop="id" label="编号" width />
      <el-table-column prop="sort" label="排序" width />
      <el-table-column prop="createdTime" label="创建时间" :formatter="formatCreatedTime" width />
      <el-table-column v-if="checkPermission(['api:material:articlecategory:update','api:material:articlecategory:softdelete'])"  label="操作" fixed="right" width>
        <template v-if="checkPermission(['api:material:articlecategory:update'])" #default="{ $index, row }">
          <el-button icon="el-icon-edit" @click="onEdit($index, row)">编辑</el-button>
          <my-confirm-button
            v-if="checkPermission(['api:material:articlecategory:softdelete'])"
            :type="'delete'"
            :icon="'el-icon-delete'"
            @click="onDelete($index, row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--列表-->

    <!--新增或编辑窗口-->
    <el-dialog
     v-if="checkPermission(['api:material:articlecategory:add','api:material:articlecategory:update'])"
     :title= dialogTitle
     :visible.sync="addOrEditFormVisible"
     :close-on-click-modal="false"
     @close="closeAddOrEditForm"
    >
      <el-form ref="addOrEditForm" :model="addOrEditForm" label-width="100px" :rules="addOrEditFormRules">
        <el-form-item prop="parentIds" label="分类父级">
          <el-cascader
            :key="addOrEditFormKey"
            v-model="addOrEditForm.parentIds"
            :options="articleCategories"
            :props="{ checkStrictly: true, label: 'name', value: 'id' }"
            filterable
            clearable
            style="width:100%;"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addOrEditForm.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="分类排序" prop="sort">
          <el-input-number v-model="addOrEditForm.sort" controls-position="right" @change="handleChange" :min="1" :max="999" auto-complete="off"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="addOrEditFormVisible = false">取消</el-button>
          <my-confirm-button type="submit" :loading="addOrEditLoading" :validate="addOrEditFormValidate" @click="onAddOrEditSubmit" />
        </div>
      </template>
    </el-dialog>
    <!--新增或编辑窗口-->
  </my-container>
</template>
<script>
import { formatTime, treeToList, listToTree, getTreeParents } from '@/utils'
import {
  getArticleCategory,
  getArticleCategoryListPage,
  getArticleCategoryList,
  addArticleCategory,
  editArticleCategory,
  removeArticleCategory
} from '@/api/material/articleCategory'
import MyContainer from '@/components/my-container'
import MyConfirmButton from '@/components/my-confirm-button'
export default {
  name: 'ArticleCategory',
  components: { MyContainer, MyConfirmButton },
  data() {
    return {
      // 查询
      filter: {
        name: ''
      },
      articleCategoryTree: [],
      articleCategories: [],
      listLoading: false,
      expandRowKeys: [],
      sels: [], // 列表选中列

      // 新增或编辑
      addOrEditFormVisible: false,
      addOrEditLoading: false,
      addOrEditFormKey: 1, 
      addOrEditForm: {
        id: '',
        parentIds: [],
        name: '',
        sort: 0
      },
      addOrEditFormRules: {
        parentIds: [{ required: true, message: '请选择分类父级', trigger: 'change' }],
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      dialogTitle: ''
    }
  },
  async mounted() {
    this.onGetList()
  },
  methods: {
    formatCreatedTime: function(row, column, time) {
      return formatTime(time, 'YYYY-MM-DD HH:mm')
    },
    // 获取列表
    async onGetList() {
      const para = {
        key: this.filter.name
      }
      this.listLoading = true
      const res = await getArticleCategoryList(para)
      this.listLoading = false

      if (!res?.success) {
        return
      }

      const list = _.cloneDeep(res.data)

      const keys = list.filter(l => l.parentId === 0).map(l => l.id + '')
      this.expandRowKeys = keys

      this.articleCategories = listToTree(_.cloneDeep(list), {
        id: 0,
        parentId: 0,
        name: '根节点'
      })

      list.forEach(d => {
        d._loading = false
      })
      const tree = listToTree(list)
      this.articleCategoryTree = tree
    },
    onSelectAll: function(selection) {
      const selections = treeToList(selection)
      const rows = treeToList(this.dictionaryTree)
      const checked = selections.length === rows.length
      rows.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row, checked)
      })

      this.sels = this.$refs.multipleTable.selection
    },
    onSelect: function(selection, row) {
      const checked = selection.some(s => s.id === row.id)
      if (row.children && row.children.length > 0) {
        const rows = treeToList(row.children)
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row, checked)
        })
      }

      this.sels = this.$refs.multipleTable.selection
    },
    // 新增
    handleAdd() {
      this.dialogTitle = "新增"
      this.addOrEditFormVisible = true
    },
    // 编辑
    async onEdit(index, row) {
      this.dialogTitle = "编辑"
      const loading = this.$loading()
      const res = await getArticleCategory({ id: row.id })

      loading.close()
      if (res && res.success) {
        const parents = getTreeParents(this.articleCategoryTree, row.id)
        const parentIds = parents.map(p => p.id)
        parentIds.unshift(0)

        const data = res.data
        data.parentIds = parentIds
        this.addOrEditForm = data
        this.addOrEditFormVisible = true
        ++this.addOrEditFormKey
      }
    },
    closeAddOrEditForm() {
      this.$refs.addOrEditForm.resetFields()
      ++this.addOrEditFormKey
    },
    addOrEditFormValidate: function() {
      let isValid = false
      this.$refs.addOrEditForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async onAddOrEditSubmit() {
      this.addOrEditLoading = true
      const para = _.cloneDeep(this.addOrEditForm)
      para.parentId = para.parentIds.pop()
      let res = null

      if (this.addOrEditForm.id==='') {
        res = await addArticleCategory(para)
      }
      else {
        if (para.id === para.parentId) {         
          this.$message({
            message: '警告，父节点不能是自己！',
            type: 'error'
          })   
          this.addOrEditLoading = false       
          return
        }
        res = await editArticleCategory(para)
      }
      this.addOrEditLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('material.addOrEditOk'),
        type: 'success'
      })

      this.$refs['addOrEditForm'].resetFields()
      this.addOrEditFormVisible = false

      this.onGetList()
    },
    async handleChange(value) {
      this.addOrEditForm.sort = value
    },
    async onDelete(index, row) {
      row._loading = true
      const para = { id: row.id }
      const res = await removeArticleCategory(para)
      row._loading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: '删除成功',
        type: 'success'
      })

      this.onGetList()
    },
  }
}
</script>
